/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/5/22.
//

#include "sql/stmt/insert_stmt.h"
#include "common/log/log.h"
#include "storage/common/db.h"
#include "storage/common/table.h"

InsertStmt::InsertStmt(Table *table, const InsertLine *lines, int lines_count)
  : table_ (table), lines_(lines), lines_count_(lines_count)
{}

void chars_to_ints(Value& v) {
  int res;
  res = atoi((const char *)v.data);
  free(v.data);

  v.type = INTS;
  v.data = malloc(sizeof(res));
  memcpy(v.data, &res, sizeof(res));
  LOG_INFO("chars_to_ints %d", *(int*)v.data);
}

void ints_to_chars(Value& v) {
  std::string res;
  res = std::to_string(*(int*)v.data);
  free(v.data);

  v.type = CHARS;
  v.data = strdup(res.c_str());
  LOG_INFO("ints_to_chars %s", v.data);
}

void chars_to_floats(Value& v) {
  float res;
  res = atof((const char *)v.data);
  free(v.data);

  v.type = FLOATS;
  v.data = malloc(sizeof(res));
  memcpy(v.data, &res, sizeof(res));
  LOG_INFO("chars_to_floats %f", *(float*)v.data);
}


static inline std::string double2string(double v)
{
  char buf[256];
  snprintf(buf, sizeof(buf), "%.2f", v);
  size_t len = strlen(buf);
  while (buf[len - 1] == '0') {
    len--;
      
  }
  if (buf[len - 1] == '.') {
    len--;
  }

  return std::string(buf, len);
}

void floats_to_chars(Value& v) {
  std::string res;
  res = double2string(*(float*)v.data);
  free(v.data);

  v.type = CHARS;
  v.data = strdup(res.c_str());
  LOG_INFO("floats_to_chars %s", v.data);
}

void ints_to_floats(Value& v) {
  float res;
  res = (float)(*(int*)v.data);
  free(v.data);

  v.type = FLOATS;
  v.data = malloc(sizeof(res));
  memcpy(v.data, &res, sizeof(res));
  LOG_INFO("ints_to_floats %f", *(float*)v.data);
}

void floats_to_ints(Value& v) {
  int res;
  res = (int)(*(float*)v.data+0.5);
  free(v.data);

  v.type = INTS;
  v.data = malloc(sizeof(res));
  memcpy(v.data, &res, sizeof(res));
  LOG_INFO("floats_to_ints %d", *(int*)v.data);
}

void chars_to_texts(Value& v) {
  char *res = (char*)malloc(TEXT_SIZE+1);
  memset(res, 0, TEXT_SIZE+1);
  strncpy(res,(char*)v.data,std::min(TEXT_SIZE, (int)strlen((char*)v.data)));
  free(v.data);

  v.type = TEXTS;
  v.data = res;
  LOG_INFO("chars_to_texts %s", v.data);
}

RC InsertStmt::create(Db *db, Inserts &inserts, Stmt *&stmt)
{
  const char *table_name = inserts.relation_name;
  LOG_INFO("InsertLines nums: %d", inserts.lines_num);
  if (nullptr == db || nullptr == table_name || inserts.lines_num <= 0) {
    LOG_WARN("invalid argument. db=%p, table_name=%p, lines_num=%d", 
             db, table_name, inserts.lines_num);
    return RC::INVALID_ARGUMENT;
  }

  // check whether the table exists
  Table *table = db->find_table(table_name);
  if (nullptr == table) {
    LOG_WARN("no such table. db=%s, table_name=%s", db->name(), table_name);
    return RC::SCHEMA_TABLE_NOT_EXIST;
  }

  // check the fields number
  InsertLine *lines = inserts.lines;
  const int lines_num = inserts.lines_num;

  
  const TableMeta &table_meta = table->table_meta();
  const int field_num = table_meta.field_num() - table_meta.sys_field_num();
  // check each line
  for (int i = 0; i<lines_num; ++i) {
    int value_num = lines[i].value_num;
    Value *values = lines[i].values;

    if (field_num != value_num) {
      LOG_WARN("schema mismatch. line num = %d value num=%d, field num in schema=%d", i, value_num, field_num);
      return RC::SCHEMA_FIELD_MISSING;
    }

    // check fields type
    const int sys_field_num = table_meta.sys_field_num();
    for (int i = 0; i < value_num; i++) {
      const FieldMeta *field_meta = table_meta.field(i + sys_field_num);
      const AttrType field_type = field_meta->type();
      const AttrType value_type = values[i].type;
      if (field_type == INTS && value_type == CHARS) {
        chars_to_ints(values[i]);
      } else if(field_type == FLOATS && value_type == CHARS) {
        chars_to_floats(values[i]);
      } else if(field_type == FLOATS && value_type == INTS) {
        ints_to_floats(values[i]);
      } else if(field_type == CHARS && value_type == FLOATS) {
        floats_to_chars(values[i]);
      } else if(field_type == INTS && value_type == FLOATS) {
        floats_to_ints(values[i]);
      } else if(field_type == CHARS && value_type == INTS) {
        ints_to_chars(values[i]);
      } else if(field_type == TEXTS && value_type == CHARS) {
        chars_to_texts(values[i]);
      } else if (field_type != value_type) { // TODO try to convert the value type to field type
        LOG_WARN("field type mismatch. table=%s, line num = %d, field=%s, field type=%d, value_type=%d", 
                table_name, i, field_meta->name(), field_type, value_type);
        return RC::SCHEMA_FIELD_TYPE_MISMATCH;
      }
    }
  }

  // everything alright
  stmt = new InsertStmt(table, lines, lines_num);
  return RC::SUCCESS;
}
